<template>
  <!-- 安全管理制度 -->
  <div class="mgtsystem">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >

        <!-- 左上方菜单 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.mgtsystem_delete"
            @click="handleDelete">
            删 除
          </el-button>

          <el-button
            type="success"
            size="small"
            plain
            icon="el-icon-upload2"
            @click="handleImport">
            导 入
          </el-button>

          <el-button
            type="warning"
            size="small"
            plain
            icon="el-icon-download"
            @click="handleExport">
            导 出
          </el-button>

          <el-button
            type="primary"
            size="small"
            plain
            icon="el-icon-delete-solid"
            @click="handleVoid">
            作 废
          </el-button>
        </template>

        <!-- 附件表单自定义 -->
        <template slot="fjForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="fjFileList"
              :before-upload="beforeUploadFJ"
              :on-remove="handleRemoveFJ"
              :on-success="uploadFJSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in fjFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 附件表格自定义 -->
        <template slot="fj" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['fj']" v-if="scope.row['fj'] !== '' && scope.row['fj'] !== undefined">
              <i class="el-icon-download"></i>下载附件
            </a>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 状态表格自定义 -->
        <template slot="status" slot-scope="scope">
          <span>{{formatStatus(scope.row)}}</span>
        </template>

        <!-- 审批表格自定义 -->
        <template slot="approve" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['auditPermissions'] && scope.row['sfzf'] !== 1"
              type="success"
              size="mini"
              @click="handleExamine(scope.row)">
              审 核
            </el-button>
            <el-button
              v-if="scope.row['approvalPermissions'] && scope.row['sfzf'] !== 1"
              type="warning"
              size="mini"
              @click="handleApprove(scope.row)">
              批 准
            </el-button>
            <span v-if="scope.row['sfzf'] === 1 || ( !scope.row['auditPermissions'] && !scope.row['approvalPermissions'] )">-</span>
          </div>
        </template>

        <!-- 评审表格自定义 -->
        <template slot="review" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['reviewPermissions'] && scope.row['sfzf'] !== 1"
              type="success"
              size="mini"
              @click="handleReview(scope.row)">
              评 审
            </el-button>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 修订表格自定义 -->
        <template slot="revise" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['revisionPermissions'] && scope.row['sfzf'] !== 1"
              type="primary"
              size="mini"
              @click="handleRevise(scope.row)">
              修 订
            </el-button>
            <el-button
              v-if="scope.row['revisionPermissions'] && scope.row['sfzf'] !== 1"
              type="warning"
              size="mini"
              @click="handleReviseRecord(scope.row)">
              修订记录
            </el-button>
            <span v-if="!scope.row['revisionPermissions'] || scope.row['sfzf'] === 1">-</span>
          </div>
        </template>
      </avue-crud>

      <!-- 导入弹窗 -->
      <el-dialog
        title="安全管理制度导入"
        append-to-body
        :visible.sync="excelBox"
        width="555px"
      >
        <avue-form
          :option="excelOption"
          v-model="excelForm"
          :upload-after="uploadAfter"
          :upload-before="beforeUpload"
          :upload-error="uploadError"
        >
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

      <!-- 评审弹窗 -->
      <el-dialog 
        title="添加安全管理制度评审信息"
        append-to-body
        :visible.sync="safeSystemReviewDialog"
        :close-on-click-modal="false" 
        :before-close="closeSafeSystemReviewDialog"
        width="60%"
        class="add_review_dialog"
      > 

        <!-- 内容 -->
        <el-form :model="reviewForm" :rules="reviewRules" ref="reviewForm" :label-position="left" label-width="80px">
          
          <!-- 评审主题 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="评审主题" prop="pszt">
                <el-input
                  size="small"
                  placeholder="请输入 评审主题"
                  v-model="reviewForm.pszt">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 评审日期 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="评审日期" prop="psrq">
                <div class="review_date">
                  <el-date-picker
                    v-model="reviewForm.psrq"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    type="date"
                    size="small"
                    placeholder="请选择 评审日期">
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>

          </el-row>

          <!-- 地点 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="地点" prop="dd">
                <el-input
                  size="small"
                  placeholder="请输入 地点"
                  v-model="reviewForm.dd">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 评审依据 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="评审依据" prop="psyj">
                <el-input
                  size="small"
                  placeholder="请输入 评审依据"
                  v-model="reviewForm.psyj">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 评审范围 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="评审范围" prop="psfw">
                <el-input
                  size="small"
                  placeholder="请输入 评审范围"
                  v-model="reviewForm.psfw">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 参评人员 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="参评人员" prop="cpry">
                <el-input
                  size="small"
                  placeholder="请输入 参评人员"
                  v-model="reviewForm.cpry">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 评审纪要 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="评审纪要" prop="psjy">
                <el-input
                  size="small"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入 评审纪要"
                  v-model="reviewForm.psjy">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 评审结论 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="评审结论" prop="psjl">
                <el-input
                  size="small"
                  placeholder="请输入 评审结论"
                  v-model="reviewForm.psjl">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 审核人、批准人 -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="审核人" prop="shren">
                <el-select 
                  v-model="reviewForm.shren" 
                  clearable 
                  placeholder="请选择审核人"
                  size="small"
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.realName"
                    :value="user.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批准人" prop="spren">
                <el-select 
                  v-model="reviewForm.spren" 
                  clearable 
                  placeholder="请选择批准人"
                  size="small"
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.realName"
                    :value="user.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 评审附件 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="评审附件" prop="psfj">
                <el-upload
                  action="/api/fileManager/upload/file"
                  :headers="SetHeaders"
                  :file-list="psfjFileList"
                  :before-upload="beforeUploadPSFJ"
                  :on-remove="handleRemovePSFJ"
                  :on-success="uploadPSFJSuccess"
                >
                  <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>

        <!-- 按钮 -->
        <div class="safe_system_review_footer">
          <el-button 
            type="primary"
            size="small"
            @click="confirmAddSafeSystemReview()">
            确 定
          </el-button>
          <el-button 
            size="small"
            @click="closeSafeSystemReviewDialog()">
            取 消
          </el-button>
        </div>
      </el-dialog>

      <!-- 审核、批准、修订弹窗 -->
      <el-dialog 
        :title="dialogTitle"
        append-to-body
        :visible.sync="updateDialog"
        :close-on-click-modal="false" 
        :before-close="closeUpdateDialog"
        width="60%"
        class="examine_approve_revise_dialog"
      > 

        <!-- 内容 -->
        <avue-form 
          ref="updateForm" 
          v-model="updateObj" 
          :option="updateOption" 
          @submit="confirmApproveOrRevise"
        >

          <!-- 附件表单自定义 -->
          <template slot="fj">
            <div>
              <el-upload
                v-if="updateDialogType === reviseStr"
                action="/api/fileManager/upload/file"
                :headers="SetHeaders"
                :file-list="xdfjFileList"
                :before-upload="beforeUploadXDFJ"
                :on-remove="handleRemoveXDFJ"
                :on-success="uploadXDFJSuccess"
              >
                <el-button 
                  size="small" 
                  type="primary" 
                  icon="el-icon-document">
                  选择文件
                </el-button>
              </el-upload>

              <a
                v-else-if="updateDialogType !== reviseStr && xdfjFileList && xdfjFileList.length > 0"
                v-for="(item, index) in xdfjFileList"
                :key="index"
                :href="downloadHead + item.response.data.id"
                style="color:#409EFF"
              >
                <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
              </a>

              <span v-else>-</span>
            </div>
          </template>

          <!-- 自定义按钮 -->
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeUpdateDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>

      </el-dialog>

      <!-- 修订记录弹窗 -->
      <el-dialog 
        title="修订记录"
        append-to-body
        :visible.sync="reviseRecordDialog"
        :close-on-click-modal="false" 
        :before-close="closeReviseRecordDialog"
        width="60%"
        class="revise_record_dialog"
      >

        <!-- 表格内容 -->
        <avue-crud 
          :option="reviseRecordOption"
          :table-loading="reviseRecordLoading"
          :data="reviseRecordData"
          :page.sync="reviseRecordPage"
          v-model="reviseRecordForm"
        >
        </avue-crud>

        <!-- 按钮 -->
        <div class="revise_record_footer">
          <el-button 
            type="primary"
            size="small"
            @click="closeReviseRecordDialog()">
            确 定
          </el-button>
        </div>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  add,
  update,
  remove,
  revise,
  getStatusList,
  invalid,
  modifyStatus,
  addReviewRecord,
  getReviseRecordList,
  getUserList
} from "@/api/securitysystemmanagement/mgtsystem";
import { getDeptTree } from "@/api/system/dept";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import {
  severityColumn,
  reviseRecordColumn,
  reviseColumn,
  exportColumn
} from "./constant/mgtsystem.js";

export default {
  data() {
    return {
      // 导入
      excelBox: false,
      excelForm: {},
      isFailed: false,
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: exportColumn
      },
      // 列表
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: severityColumn
      },
      // 附件
      dialogType: "",
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      fjFileList: [],
      statusObj: {},
      // 评审弹窗
      safeSystemReviewDialog: false,
      reviewObjId: "",
      reviewForm: {
        pszt: "",
        psrq: "",
        dd: "",
        psyj: "",
        psfw: "",
        cpry: "",
        psjy: "",
        psjl: "",
        psfj: ""
      },
      reviewRules: {
        pszt: [{ required: true, message: '请输入评审主题', trigger: 'blur' }],
        shren: [{ required: true, message: '请选择审核人', trigger: 'blur' }],
        spren: [{ required: true, message: '请选择批准人', trigger: 'blur' }]
      },
      // 评审附件
      psfjFileList: [],
      // 修订附件
      xdfjFileList: [],
      // 审核、批准、修订弹窗
      updateDialogType: "",
      examineStr: "EXAMINE",
      approveStr: "APPROVE",
      reviseStr: "REVISE",
      dialogTitle: "",
      updateDialog: false,
      updateObj: {},
      userList: [],
      // 修订记录弹窗
      reviseRecordDialog: false,
      reviseRecordId: "",
      reviseRecordForm: {},
      reviseRecordLoading: true,
      reviseRecordQuery: {},
      reviseRecordData: [],
      reviseRecordPage: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      reviseRecordOption: {
        calcHeight: 30,
        tip: false,
        index: false,
        selection: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        menu: false,
        column: reviseRecordColumn
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.mgtsystem_add, false),
        viewBtn: this.vaildData(this.permission.mgtsystem_view, false),
        delBtn: this.vaildData(this.permission.mgtsystem_delete, false),
        editBtn: this.vaildData(this.permission.mgtsystem_edit, false)
      };
    },

    // 勾选项id
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },

    updateOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: reviseColumn
      } 
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化页面
    initData() {
      var tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;
      getDeptTree(tenantId).then(res => {
        const bjbmColumn = this.findObject(this.option.column, "bjbm");
        const sybmColumn = this.findObject(this.option.column, "sybm");
        const bjbmAvueColumn = this.findObject(this.updateOption.column, "bjbm");
        const sybmAvueColumn = this.findObject(this.updateOption.column, "sybm");
        bjbmColumn.dicData = res.data.data;
        sybmColumn.dicData = res.data.data;
        bjbmAvueColumn.dicData = res.data.data;
        sybmAvueColumn.dicData = res.data.data;
      }).then(() => {
        getStatusList().then(res => {
          this.statusObj = {};
          res.data.data.forEach(item => {
            this.statusObj[item.dictKey] = item.dictValue;
          });
        }).then(() => {
          this.onLoad(this.page);
          this.getUsers();
        });
      });
    },

    // 获取人员列表
    getUsers() {
      getUserList().then(res => {
        this.userList = res.data.data;
      });
    },

    // 格式化状态列
    formatStatus(row) {
      var sfzf = row.sfzf;
      var zt = row.zt;
      if(sfzf === 1) {
        return "已作废";
      } else {
        return this.statusObj[zt];
      }
    },

    /**
     * 导入导出
    */

    // 弹出导入框
    handleImport() {
      this.excelBox = true;
    },

    // 导入前判断
    beforeUpload(file, done, loading) {
      this.isFailed = false;
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "xls";
      const extension2 = testmsg === "xlsx";
      if (!extension && !extension2) {
        this.$message.warning("请上传 .xls,.xlsx 标准格式文件!");
        loading();
      } else {
        done();
      }
    },

    // 模板下载
    handleTemplate() {
      window.open(`/api/securitySystemManagement/mgtsystem/exportTemplate?${this.website.tokenHeader}=${getToken()}`);
    },

    // 导入失败后
    uploadError(error, column) {
      console.log(error, column);
      this.isFailed = true;
    },

    // 导入成功后
    uploadAfter(res, done) {
      done();
      if (this.isFailed === true) {
        return;
      }
      this.excelBox = false;
      this.$message.success("上传成功");
      this.cancle();
    },

    // 取消
    cancle() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 点击导出按钮
    handleExport() {
      this.$confirm("是否导出安全管理制度?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let zdmc = this.query.zdmc === undefined || this.query.zdmc === null ? "" : this.query.zdmc;
        window.open(`/api/securitySystemManagement/mgtsystem/export?${this.website.tokenHeader}=${getToken()}&zdmc=${zdmc}`);
      });
    },

    // 点击作废按钮
    handleVoid() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据作废?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return invalid(this.ids);
      }).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.$refs.crud.toggleSelection();
      });
    },

    /**
     * 安全管理制度列表操作
    */

    // 新增
    rowSave(row, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.bjbm = row.bjbm.join(",");
      row.sybm = row.sybm.join(",");
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.bjbm = typeof row.bjbm === "object" ? row.bjbm.join(",") : row.bjbm;
      row.sybm = typeof row.sybm === "object" ? row.sybm.join(",") : row.sybm;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开新增、修改、查看弹窗前
    beforeOpen(done, type) {
      if(type === "edit") {
        if(this.form.sfzf === 1) {
          this.$message.warning("当前制度已作废!");
          return;
        }
        if(!this.form.editPermissions) {
          this.$message.warning("当前制度不可编辑!");
          return;
        }
      }
      this.dialogType = type;
      this.fjFileList = [];
      if (["edit", "view"].includes(type)) {
        if (this.form.fj && this.form.bladeFiles && JSON.stringify(this.form.bladeFiles) !== "{}") {
          this.fjFileList.push({
            name: this.form.bladeFiles.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: this.form.bladeFiles
            }
          });
        }
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传附件
     */

    // 上传附件前
    beforeUploadFJ(file) {
      console.log(file);
      var isLimit = this.fjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传附件成功
    uploadFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.fjFileList = fileList;
      this.form.fj = response.data.id;
    },

    // 删除附件
    handleRemoveFJ(file, fileList) {
      this.fjFileList = fileList;
      this.form.fj = "";
    },

    /**
     * 上传评审附件
     */

    // 上传评审附件前
    beforeUploadPSFJ(file) {
      console.log(file);
      var isLimit = this.psfjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传评审附件成功
    uploadPSFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.psfjFileList = fileList;
      this.reviewForm.psfj = response.data.id;
    },

    // 删除评审附件
    handleRemovePSFJ(file, fileList) {
      this.psfjFileList = fileList;
      this.reviewForm.psfj = "";
    },

    /**
     * 上传修订附件
     */

    // 上传修订附件前
    beforeUploadXDFJ(file) {
      console.log(file);
      var isLimit = this.xdfjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传修订附件成功
    uploadXDFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.xdfjFileList = fileList;
      this.updateObj.fj = response.data.id;
    },

    // 删除修订附件
    handleRemoveXDFJ(file, fileList) {
      this.xdfjFileList = fileList;
      this.updateObj.fj = "";
    },

    /**
     * 评审弹窗
    */

    // 打开评审弹窗
    handleReview(row) {
      this.reviewObjId = row.id;
      this.safeSystemReviewDialog = true;
    },

    // 关闭、取消评审弹窗
    closeSafeSystemReviewDialog() {
      this.reviewForm = {
        pszt: "",
        psrq: "",
        dd: "",
        psyj: "",
        psfw: "",
        cpry: "",
        psjy: "",
        psjl: "",
        psfj: ""
      };
      this.psfjFileList = [];
      this.reviewObjId = "";
      this.safeSystemReviewDialog = false;
    },

    // 点击确认添加评审按钮
    confirmAddSafeSystemReview() {
      this.$refs["reviewForm"].validate((valid) => {
        if (valid) {
          this.reviewForm["reviewObjId"] = this.reviewObjId;
          addReviewRecord(this.reviewForm).then(res => {
            if(res.data.success) {
              this.closeSafeSystemReviewDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      });
    },

    // 打开审核弹窗
    handleExamine(row) {
      this.updateDialogType = this.examineStr;
      this.updateDialog = true;
      this.dialogTitle = "审核安全管理制度";
      this.updateObj = this.formatUpdateForm(row);
      this.xdfjFileList = [];
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "{}") {
        this.xdfjFileList.push({
          name: row.bladeFiles.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.bladeFiles
          }
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop !== "deptExamine" && item.prop !== "leaderApprove") {
          item.disabled = true;
        }
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = false;
        }
        if(item.prop === "leaderApprove") {
          item.display = false;
          item.disabled = true;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 打开批准弹窗
    handleApprove(row) {
      this.updateDialogType = this.approveStr;
      this.updateDialog = true;
      this.dialogTitle = "批准安全管理制度";
      this.updateObj = this.formatUpdateForm(row);
      this.xdfjFileList = [];
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "{}") {
        this.xdfjFileList.push({
          name: row.bladeFiles.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.bladeFiles
          }
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop !== "deptExamine" && item.prop !== "leaderApprove") {
          item.disabled = true;
        }
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = true;
        }
        if(item.prop === "leaderApprove") {
          item.display = true;
          item.disabled = false;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 打开修订弹窗
    handleRevise(row) {
      this.updateDialogType = this.reviseStr;
      this.updateDialog = true;
      this.dialogTitle = "修订安全管理制度";
      this.updateObj = this.formatUpdateForm(row);
      this.xdfjFileList = [];
      if (row.fj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "{}") {
        this.xdfjFileList.push({
          name: row.bladeFiles.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.bladeFiles
          }
        });
      }
      this.updateOption.column.forEach(item => {
        if (!["deptExamine", "leaderApprove", "shren", "spren", "psren"].includes(item.prop)) {
          item.disabled = false;
        }
        if(item.prop === "deptExamine" || item.prop === "leaderApprove") {
          item.display = false;
          item.disabled = true;
        }
      });
    },

    // 格式化审核、批准、修订弹窗表单数据
    formatUpdateForm(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      return data;
    },

    // 获取部门审核、领导批准字段值
    formatExamineApproveValue(obj) {
      if(obj.zt === 0) {
        obj["deptExamine"] = "";
        obj["leaderApprove"] = "";
      } else if(obj.zt === 1) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 2) {
        obj["deptExamine"] = 2;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 3) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 1;
      } else if(obj.zt === 4) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 2;
      }
    },

    // 关闭、取消审核&批准&修订弹窗
    closeUpdateDialog() {
      this.updateObj = {};
      this.xdfjFileList = [];
      this.updateDialogType = "";
      this.updateDialog = false;
      this.dialogTitle = "";
    },

    // 确定审核、批准、修订
    confirmApproveOrRevise() {
      if(this.updateDialogType === this.examineStr) {
        this.confirmExamine();
      } else if(this.updateDialogType === this.approveStr) {
        this.confirmApprove();
      } else if(this.updateDialogType === this.reviseStr) {
        this.confirmRevise();
      }
    },

    // 确认审核
    confirmExamine() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.deptExamine).then(res => {
            if(res.data.success) {
              done();
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      })
    },

    // 确认批准
    confirmApprove() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.leaderApprove).then(res => {
            if(res.data.success) {
              done();
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      })
    },

    // 确认修订
    confirmRevise() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          var updateRow = this.formatReviseData(this.updateObj);
          revise(updateRow).then(res => {
            if(res.data.success) {
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 获取修订时的数据
    formatReviseData(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      data["bjbm"] = typeof row.bjbm === "object" ? row.bjbm.join(",") : row.bjbm;
      data["sybm"] = typeof row.sybm === "object" ? row.sybm.join(",") : row.sybm;
      return data;
    },

    // 打开修订记录弹窗
    handleReviseRecord(row) {
      this.reviseRecordId = row.id;
      this.reviseRecordDialog = true;
      this.reviseRecordPage.currentPage = 1;
      this.reviseRecordOnLoad(this.reviseRecordPage);
    },

    // 获取修订记录列表
    reviseRecordOnLoad(page, params = {}) {
      this.reviseRecordLoading = true;
      this.reviseRecordQuery = {safetyMgtSystemId: this.reviseRecordId};
      getReviseRecordList(page.currentPage, page.pageSize, Object.assign(params, this.reviseRecordQuery)).then(res => {
        var resData = res.data.data;
        this.reviseRecordPage.total = resData.total;
        this.reviseRecordData = resData.records;
        this.reviseRecordLoading = false;
      });
    },

    // 确认、取消、关闭修订记录弹窗
    closeReviseRecordDialog() {
      this.reviseRecordDialog = false;
      this.reviseRecordId = "";
    }

  }
};
</script>

<style lang="scss" scpoed>
.mgtsystem {
  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      i {
        margin-right: 5px;
      }
    }
  }
}

.safe_system_review_footer,
.approve_revise_footer,
.revise_record_footer {
  text-align: center;
  margin-top: 15px;

  .el-button {
    width: 100px;
    height: 35px;
  }
}

.review_date,
.fbrq_div,
.qyrq_div {
  .el-date-editor.el-input {
    width: 100%;
  }
}

.examine_approve_revise_dialog {
  .avue-form__menu--center {
    text-align: center;
  }
}

.revise_record_dialog {
  .avue-crud__menu,
  .avue-crud__pagination {
    display: none;
  }
}

.add_review_dialog {
  .el-select {
    width: 100%;
  }
}
</style>